#include "dlgmain.h"
#include "ui_dlgmain.h"

#include "tmglobalctrl.h"

typedef IceUtil::Handle<TMMySessionCB> MySessionCBPtr;

DlgMain::DlgMain(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DlgMain)
{
    ui->setupUi(this);

    //去掉窗口右上角的问号
    Qt::WindowFlags flags=Qt::Dialog;
    flags |=Qt::WindowCloseButtonHint;
    flags |=Qt::WindowMinimizeButtonHint;
    this->setWindowFlags(flags);

    QString g_strRootDir = QCoreApplication::applicationDirPath();
    QDir::setCurrent(g_strRootDir);

    init();

}

DlgMain::~DlgMain()
{
    delete ui;
}

void DlgMain::init()
{
    for(int i = 0;i < 50;i++){
        ui->comboBox_B->addItem(QString("%1").arg(i));
        ui->comboBox_F->addItem(QString("%1").arg(i));
    }

    read_xls_tts();
    pr_DlgMain = this;
    m_strMoveFlag = "";
    connect(this,SIGNAL(sig_sendTTS(QString)),this,SLOT(slot_sendTTS(QString)));

    pr_DlgLogin = new DlgLogin();
    pr_DlgLogin->show();
    connect(pr_DlgLogin,SIGNAL(sig_conn(QString)),this,SLOT(slot_conn(QString)));
    connect(pr_DlgLogin,SIGNAL(sig_cancel()),this,SLOT(slot_cancel()));

//    myThread = new QThread;
    pr_RTMPCtrl = new TMRTMPCtrl;
//    pr_RTMPCtrl->moveToThread(myThread);
    connect(this,SIGNAL(sig_getVideoLive(QString,QLabel*)),pr_RTMPCtrl,SLOT(slot_getVideoLive(QString,QLabel*)));
    connect(this,SIGNAL(sig_startAudioLive(QString)),pr_RTMPCtrl,SLOT(slot_startAudioLive(QString)));
    connect(this,SIGNAL(sig_stopVideoLive()),pr_RTMPCtrl,SLOT(slot_stopVideoLive()));
    connect(this,SIGNAL(sig_stopAudioLive()),pr_RTMPCtrl,SLOT(slot_stopAudioLive()));
//    myThread->start();

    pr_TtsStateTimer = new QTimer();
    connect(pr_TtsStateTimer,SIGNAL(timeout()),this,SLOT(slot_getTtsState()));
    pr_ScriptStateTimer = new QTimer();
    connect(pr_ScriptStateTimer,SIGNAL(timeout()),this,SLOT(slot_getScriptState()));

    pr_MotorTimer = new QTimer();
    connect(pr_MotorTimer,SIGNAL(timeout()),this,SLOT(slot_moveCtrl()));

    connect(this,SIGNAL(sig_msgBox(QString)),this,SLOT(slot_msgBox(QString)));
}

void DlgMain::read_xls_tts()
{
    if(!m_csvTTS.loadFile(ROBOT_TTS_FILENAME)){
        QMessageBox::warning(this, "File Load Error", QString("can not find:%1").arg(ROBOT_TTS_FILENAME));
        return;
    }
    // update ui
    ui->list_class->clear();
    ui->list_content->clear();
    QStringList nameList = m_csvTTS.getTextRow(0);
    foreach (QString name, nameList) {
        if(name.length()>0){
            ui->list_class->addItem(name);
        }
    }
    if( nameList.size()>0 ){
        ui->list_class->setCurrentRow(0);
    }
}

void DlgMain::move_control(bool bStart, QString strCmd)
{
    if( bStart ){
        m_strMoveFlag = strCmd;
        pr_MotorTimer->start(600);
    }else{
        m_strMoveFlag = "";
        pr_MotorTimer->stop();
        try{
            m_prxMotor->WheelStop(false);
        }catch(Ice::Exception& e)
        {
            qDebug()<<"Error:"<<e.what();
            emit sig_msgBox(e.what());
        }
    }
}


//强制结束关闭程序处理
void DlgMain::closeEvent(QCloseEvent *e)
{
    if(pr_TtsStateTimer)
        pr_TtsStateTimer->stop();
    if(pr_ScriptStateTimer)
        pr_ScriptStateTimer->stop();
    if(pr_MotorTimer)
        pr_MotorTimer->stop();


    conFlag = 1;
    destoryIce();

}

void DlgMain::destoryIce()
{
    if(_session){
        _session->destroy();
        _session = NULL;
    }
    for(int i = 0;i < 100;i++){
        QCoreApplication::processEvents();
        QThread::msleep(5);
    }
    if(_factory){
        _factory->destroy();
        _factory = NULL;
    }
    qDebug()<<"destroy session and factory";
}

void DlgMain::slot_conn(QString m_ip)
{
    m_connIP = m_ip;

//    QString m_Locator = QString("--Ice.Default.Router=Glacier2/router:tcp -p 8989 -h %1 -t 3000\r\n").arg(m_ip);
//    QString m_TopicManager = QString("--TopicManager.Proxy=PubCenter/TopicManager");

//    Ice::StringSeq argList;
//    argList.push_back(m_Locator.toUtf8().toStdString());
//    argList.push_back(m_TopicManager.toUtf8().toStdString());
//    m_icePtr = Ice::initialize(argList);
    Ice::InitializationData iniData;
    iniData.properties = Ice::createProperties();
    iniData.properties->setProperty(QString("Ice.Default.Router").toUtf8().toStdString(), QString("Glacier2/router:tcp -p 8989 -h %1 -t 2000\r\n").arg(m_ip).toUtf8().toStdString());
//    iniData.properties->setProperty("RobotPort.Endpoints", "tcp -h 127.0.0.1 -p 9090");
//    iniData.properties->setProperty("RobotPort.Endpoints", "tcp -h 127.0.0.1 -p 9090");

    MySessionCBPtr cbSession = new TMMySessionCB(this);
    _factory = new Glacier2::SessionFactoryHelper(iniData, cbSession);
//    qDebug()<<"timeout:"<<_factory->getTimeout();
//    _factory->setTimeout(2000);//不管用
    _session = _factory->connect("aa", "bb");
}

void DlgMain::slot_cancel()
{
    pr_DlgLogin->close();
    this->close();
}
//链接成功处理
void DlgMain::slot_connSuccess()
{
    this->show();
    pr_DlgLogin->hide();   
//    emit sig_getVideoLive(m_connIP,ui->label);
    ui->checkBox_video->setChecked(false);
    ui->Btn_talk->setText("开启通话");
    try
    {
        m_prxJson = Robot::JsonPrx::checkedCast(_session->communicator()->stringToProxy("Json"));
        m_prxMotor = Robot::MotorPrx::checkedCast(_session->communicator()->stringToProxy("Motor"));
        m_prxAudio = Robot::AudioPrx::checkedCast(_session->communicator()->stringToProxy("Audio"));
        //        m_prxScreenEx = Robot::ScreenExPrx::checkedCast(_session->communicator()->stringToProxy("ScreenEx"));
        m_prxConfig = Robot::ConfigPrx::checkedCast(_session->communicator()->stringToProxy("Config"));
        m_prxPub = Robot::PubPrx::checkedCast(_session->communicator()->stringToProxy("Pub"));
        m_prxSession = Robot::SessionPrx::checkedCast(_session->communicator()->stringToProxy("Session"));
        m_prxLive = Robot::LivePrx::checkedCast(_session->communicator()->stringToProxy("Live"));
        m_prxScript = Robot::ScriptPrx::checkedCast(_session->communicator()->stringToProxy("Script"));
        m_prxFileMgr = Robot::FileMgrPrx::checkedCast(_session->communicator()->stringToProxy("FileMgr"));
        _robotSession = Robot::SessionPrx::checkedCast(_session->communicator()->stringToProxy("Session"));

        try{
            bool m_bProtectState = m_prxMotor->GetProtect();
            if(m_bProtectState){
                ui->checkBox_avoidOpen->setChecked(true);
            }else{
                ui->checkBox_avoidOpen->setChecked(false);
            }
        }catch(Ice::Exception& e)
        {
            qDebug()<<"Error:"<<e.what();
            emit sig_msgBox(e.what());
        }
        pr_TtsStateTimer->start(500);
        pr_ScriptStateTimer->start(500);
    }catch(Ice::Exception& e){
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
        return;
    }
}

void DlgMain::slot_connFailed()
{
    destoryIce();
    emit sig_msgBox("连接失败!");
}
//连接断开处理
void DlgMain::slot_disConnected()
{
    qDebug()<<"conFlag::"<<conFlag;

    emit sig_stopAudioLive();
    emit sig_stopVideoLive();
    if(conFlag == 1){
        pr_DlgLogin->close();
        this->close();
        qDebug()<<"close!";
    }else{
        if(pr_TtsStateTimer)
            pr_TtsStateTimer->stop();
        if(pr_ScriptStateTimer)
            pr_ScriptStateTimer->stop();
        if(pr_MotorTimer)
            pr_MotorTimer->stop();

        destoryIce();
        emit sig_msgBox("连接断开!");
        this->hide();
        pr_DlgLogin->show();
    }

}

void DlgMain::slot_msgBox(QString strMsg)
{
    QMessageBox::warning(this, tr("ERROR"),strMsg,QMessageBox::Ok);
}

void DlgMain::slot_sendTTS(QString strTTS)
{
    try{
        m_prxAudio->TtsPlay(strTTS.toUtf8().toStdString());
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::slot_getTtsState()
{
    try{
        bool m_bIsPlaying = m_prxAudio->TtsIsPlaying();
        if(m_bIsPlaying){
            ui->label_ttsState->setText("playing");
        }else{
            ui->label_ttsState->setText("stopped");
        }
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
//        emit sig_msgBox(e.what());
        return;
    }
}

void DlgMain::slot_getScriptState()
{
    try{
        bool m_state = m_prxScript->IsPlaying();
        if(m_state){
            ui->label_scriptState->setText("playing");
        }else{
            ui->label_scriptState->setText("stopped");
        }
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
//        emit sig_msgBox(e.what());
        return;
    }
}

void DlgMain::on_btn_tts_reload_clicked()
{
    read_xls_tts();
}

void DlgMain::on_btn_tts_edit_clicked()
{
    QDesktopServices bs;
    QDir dir(ROBOT_TTS_FILENAME);
    if(!bs.openUrl(QUrl::fromLocalFile(dir.absolutePath())))
    {
        QMessageBox::warning(this, "提示", QString( "打开TTS配置文件失败"));
    }
}

void DlgMain::on_lineEdit_search_textEdited(const QString &arg1)
{
    if( arg1.length()<1 ){
        ui->list_class->setCurrentRow(0);
        return;
    }
    QStringList strFindList;
    QList<QStringList> srcList = m_csvTTS.getDataList();
    for(int i=0; i<srcList.size(); i++){
        if(i==0)
            continue;
        foreach (const QString &strOne, srcList[i]) {
            if( strOne.contains(arg1) ){
                strFindList.append(strOne);
            }
        }
    }
    ui->list_content->clear();
    foreach (const QString &strFinded, strFindList) {
        if(strFinded.length()>0){
            ui->list_content->addItem(strFinded);
        }
    }
}

void DlgMain::on_list_class_currentRowChanged(int currentRow)
{
    if( currentRow<0 ){
        return;
    }
    ui->list_content->clear();
    QStringList strlistColum = m_csvTTS.getTextColum(currentRow);
    for(int i=0; i<strlistColum.size();i++){
        if(i==0) continue;
        if( strlistColum[i].length()>0){
            ui->list_content->addItem(strlistColum[i]);
        }
    }
}

void DlgMain::on_list_content_itemClicked(QListWidgetItem *item)
{
    ui->lineEdit_tts->setText(item->text());
}

void DlgMain::on_list_content_itemDoubleClicked(QListWidgetItem *item)
{
    emit sig_sendTTS(item->text());
}

void DlgMain::on_Btn_tts_clicked()
{
    QString str_tts = ui->lineEdit_tts->text();
    emit sig_sendTTS(str_tts);
}

void DlgMain::on_Btn_script_clicked()
{
    QString strContent = ui->textEdit_script->toPlainText();
    try{
        m_prxScript->PlayContent(strContent.toUtf8().toStdString());
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::on_Btn_face_clicked()
{
    int nIndexF = ui->comboBox_F->currentIndex();
    int nIndexB = ui->comboBox_B->currentIndex();
    try{
        m_prxMotor->HeadEye(nIndexF,nIndexB);
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::on_checkBox_avoidOpen_clicked(bool checked)
{
    try{
        m_prxMotor->SetProtect(checked);
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::slot_moveCtrl()
{
    if( m_strMoveFlag == "up" ){
        try{
            m_prxMotor->WheelRun(1000,6);
        }catch(Ice::Exception& e)
        {
            qDebug()<<"Error:"<<e.what();
            emit sig_msgBox(e.what());
        }
    }
    if( m_strMoveFlag == "down" ){
        try{
            m_prxMotor->WheelRun(-1000,6);
        }catch(Ice::Exception& e)
        {
            qDebug()<<"Error:"<<e.what();
            emit sig_msgBox(e.what());
        }
    }
    if( m_strMoveFlag == "left" ){
        try{
            m_prxMotor->WheelRotate(-30,2);
        }catch(Ice::Exception& e)
        {
            qDebug()<<"Error:"<<e.what();
            emit sig_msgBox(e.what());
        }
    }
    if( m_strMoveFlag == "right" ){
        try{
            m_prxMotor->WheelRotate(30,2);
        }catch(Ice::Exception& e)
        {
            qDebug()<<"Error:"<<e.what();
            emit sig_msgBox(e.what());
        }
    }
}

void DlgMain::on_btn_move_up_pressed()
{
    move_control(true, "up");
}

void DlgMain::on_btn_move_up_released()
{
    move_control(false,"");
}

void DlgMain::on_btn_move_down_pressed()
{
    move_control(true, "down");
}

void DlgMain::on_btn_move_down_released()
{
    move_control(false,"");
}

void DlgMain::on_btn_move_left_pressed()
{
    move_control(true, "left");
}

void DlgMain::on_btn_move_left_released()
{
    move_control(false,"");
}

void DlgMain::on_btn_move_right_pressed()
{
    move_control(true, "right");
}

void DlgMain::on_btn_move_right_released()
{
    move_control(false,"");
}

void DlgMain::on_btn_stop_slow_clicked()
{
    try{
        m_prxMotor->WheelStop(true);
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::on_btn_stop_fast_clicked()
{
    try{
        m_prxMotor->WheelStop(false);
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::on_btn_power_on_clicked()
{
    try{
        m_prxMotor->WheelEnable(true);
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::on_btn_power_off_clicked()
{
    try{
        m_prxMotor->WheelEnable(false);
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::on_Btn_talk_press_pressed()
{
    ui->Btn_talk->setText("开启通话");
    emit sig_stopAudioLive();
    ui->Btn_talk_press->setText("松开停止");
    emit sig_startAudioLive(m_connIP);
    m_prxLive->RemoteRecvStart();
}

void DlgMain::on_Btn_talk_press_released()
{

    ui->Btn_talk_press->setText("按下说话");
    emit sig_stopAudioLive();
    m_prxLive->RemoteRecvStop();
}

void DlgMain::on_Btn_talk_clicked()
{
    if(ui->Btn_talk->text() == "开启通话"){
        ui->Btn_talk->setText("关闭通话");
        emit sig_startAudioLive(m_connIP);
        m_prxLive->RemoteRecvStart();
    }else{
        ui->Btn_talk->setText("开启通话");
        emit sig_stopAudioLive();
        m_prxLive->RemoteRecvStop();
    }
}

void DlgMain::on_checkBox_video_clicked(bool checked)
{
    if(checked){
        emit sig_getVideoLive(m_connIP,ui->label);
    }else{
        emit sig_stopVideoLive();
        ui->label->clear();
    }
}


void DlgMain::on_Btn_getDir_clicked()
{
    try{
        std::string strDirPath = m_prxFileMgr->GetDirPath();
        QString strPath = QString::fromUtf8(strDirPath.c_str(),strDirPath.length());
        ui->label_dirPath->setText(strPath);
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}

void DlgMain::on_Btn_getList_clicked()
{
    std::vector<std::string> m_strList;
    try{
        m_prxFileMgr->List(m_strList);
    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
    ui->listWidget->clear();
    for(int i = 0;i < m_strList.size();i++){
        std::string str = m_strList.at(i);
        QString strData = QString::fromUtf8(str.c_str(),str.length());
        ui->listWidget->insertItem(i,strData);
    }
}

void DlgMain::on_Btn_delete_clicked()
{
    try{
        if(!ui->listWidget->currentItem())
            return;
        QString strData = ui->listWidget->currentItem()->text();
        ui->listWidget->takeItem(ui->listWidget->currentRow());
        m_prxFileMgr->Delete(strData.toUtf8().toStdString());

    }catch(Ice::Exception& e)
    {
        qDebug()<<"Error:"<<e.what();
        emit sig_msgBox(e.what());
    }
}





